package communication;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

public class FileAcceptorConnection {

	private ServerConnection serverSocket;
	
	public FileAcceptorConnection(int port) throws IOException {
		
		serverSocket = new ServerConnection(port);
	
	}

	public void close() throws IOException {
		serverSocket.close();
	}
	
	public void acceptFile(String fileName)
	{
		try {
			//The person accepting a file needs to open up a socket and waits for the sender to connect to send
			SocketConnection socket = serverSocket.accept();
			
			
			//The input streams are needed to figure out what type of file it is
			DataInputStream in = new DataInputStream(socket.getInputStream());
	    	
			String fileReceived;
			
	    	fileReceived = in.readUTF();
	    	
	    	//Store the file extension
	    	String fileExt = fileReceived.substring(fileReceived.indexOf("."), fileReceived.length());
	    	
	    	
	    	
	    	//Get the sender's stream
    	  	BufferedInputStream buffIn = new BufferedInputStream(socket.getInputStream());
	    	
    	  	//The fileName should be manipulated by the UI
	    	BufferedOutputStream buffOt = new BufferedOutputStream(new FileOutputStream(new File(fileName + fileExt)));
	    	
	    	byte [] b = new byte[4096];
	    	int bytesRead;
	    	
	    	//While there's still something left to read....
	    	while ((bytesRead = buffIn.read(b)) != -1) {
	    		buffOt.write(b,0,bytesRead);
	    	}
	    	buffOt.flush();

	    	buffOt.close();
	    	buffIn.close();
	    	
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		
	}

	
}
